package com.dzz.sjgl.utils;


import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author KRIC
 * @ClassName HttpUtil
 * @Date: 2018/9/18 9:21
 * @Description:
 */
public class HttpUtil {


    /**
     * 发起get请求
     */
    public static String httpGet(String url) {
        String result = null;
        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(50000, TimeUnit.MILLISECONDS)
                .readTimeout(50000, TimeUnit.MILLISECONDS)
                .build();
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body() != null ? response.body().string() : null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送httpPost请求
     *
     * @param data 提交的参数为key=value&key1=value1的形式
     */
    public static String httpPost(String url, String data) {
        String result = null;
        OkHttpClient httpClient = new OkHttpClient().newBuilder().connectTimeout(50000, TimeUnit.MILLISECONDS)
                .readTimeout(50000, TimeUnit.MILLISECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), data);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            Response response = httpClient.newCall(request).execute();
            result = response.body() != null ? response.body().string() : null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
